package com.bootdo.clouddo.controller.common;

import com.bootdo.clouddo.core.security.OpenSDKAccessTokenUtil;
import com.bootdo.clouddo.core.security.RedisAccessTokenStore;
import com.bootdo.clouddo.domain.user.QaUsers;
import com.bootdo.clouddo.redis.CommonRedisService;
import com.bootdo.clouddo.service.user.IUserService;
import com.bootdo.clouddo.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
public class CommonController {
	
	public static final	Logger logger=LoggerFactory.getLogger(CommonController.class);
	
	@Autowired
	private RedisAccessTokenStore tokenStore;
	
	@Autowired
	protected CommonRedisService redisService;
	
	@Autowired
	protected IUserService userService;

	private final static String VCODE_KEY = "VERIFICATION_CODE_KEY_";

	/**
	 * 获取当前已经登陆的用户信息
	 * @param request
	 * 	
	 * @return
	 * 	如果没有登陆，返回null;如果已经登陆，返回当前登陆的用户
	 */
	protected QaUsers getCurrentLoginedUser(HttpServletRequest request){
		String accessToken = OpenSDKAccessTokenUtil.getAccessToken(request);
		if(accessToken == null || accessToken.trim().equals("")) {
			return null;
		}
		QaUsers user = OpenSDKAccessTokenUtil.getSecureObjectFromToken(tokenStore, accessToken);
		return user;
	}

	protected QaUsers refreshTokenUser(HttpServletRequest request, QaUsers user){
		String accessToken = OpenSDKAccessTokenUtil.getAccessToken(request);
		return OpenSDKAccessTokenUtil.refreshTokenUser(tokenStore, accessToken, user);
	}
	
	protected QaUsers getCurrentLoginedUser() {
		return getCurrentLoginedUser(getRequest());
	}
	
	/**
	 * 检查算数验证码
	 * @param result
	 * @return
	 */
	protected boolean checkVcode (String token, int result) {
		try {
			int redisResult = (Integer)redisService.get(VCODE_KEY + token);
			if(result == redisResult) {
				redisService.remove(VCODE_KEY + token);
				return true;
			} else {
				redisService.remove(VCODE_KEY + token);
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		
	}
	
	public final static String getIpAddress(HttpServletRequest request) throws IOException {
		try {
			String ip = request.getHeader("X-Forwarded-For");
			if (logger.isInfoEnabled()) {
				logger.info("getIpAddress(HttpServletRequest) - X-Forwarded-For - String ip=" + ip);
			}

			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("Proxy-Client-IP");
					if (logger.isInfoEnabled()) {
						logger.info("getIpAddress(HttpServletRequest) - Proxy-Client-IP - String ip=" + ip);
					}
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("WL-Proxy-Client-IP");
					if (logger.isInfoEnabled()) {
						logger.info("getIpAddress(HttpServletRequest) - WL-Proxy-Client-IP - String ip=" + ip);
					}
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("HTTP_CLIENT_IP");
					if (logger.isInfoEnabled()) {
						logger.info("getIpAddress(HttpServletRequest) - HTTP_CLIENT_IP - String ip=" + ip);
					}
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getHeader("HTTP_X_FORWARDED_FOR");
					if (logger.isInfoEnabled()) {
						logger.info("getIpAddress(HttpServletRequest) - HTTP_X_FORWARDED_FOR - String ip=" + ip);
					}
				}
				if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
					ip = request.getRemoteAddr();
					if (logger.isInfoEnabled()) {
						logger.info("getIpAddress(HttpServletRequest) - getRemoteAddr - String ip=" + ip);
					}
				}
			} else if (ip.length() > 15) {
				String[] ips = ip.split(",");
				for (int index = 0; index < ips.length; index++) {
					String strIp = ips[index];
					if (!("unknown".equalsIgnoreCase(strIp))) {
						ip = strIp;
						break;
					}
				}
			}
			if(StringUtils.isBlank(ip)) {
				logger.info("the ip is null - String ip=" + ip);
				ip = "127.0.0.1";
				logger.info("the ip setting default 127.0.0.1 - String ip=" + ip);
			}
			System.out.println(ip);
			return ip;
		} catch (Exception e) {
			e.printStackTrace();
			return "127.0.0.1";
		}
	}
	
	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
	}

	/**
	 * 获取用户登录名
	 * @return
	 */
	public String getUserName(){
		try{
			QaUsers user = getCurrentLoginedUser();
			return user != null ? user.getUserName() : null;
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取用户登录名
	 * @return
	 */
	public String getWxOpenid(){
		try{
			QaUsers user = getCurrentLoginedUser();
			return user != null ? user.getWxOpenid() : null;
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	public void renderToView(String type, String text, HttpServletResponse response){
		try {
			response.setContentType(type + ";charset=UTF-8");
			response.getWriter().write(text);
		} catch (Exception e) {
			logger.error("向response中写入数据失败，失败原因："+e.getMessage());
		}
	}
	
	public void renderToText(String text, HttpServletResponse response){
		renderToView("text/plain", text, response);
	}
	
	public void renderToJson(String text, HttpServletResponse response){
		renderToView("application/json", text, response);
	}
	
	/**
	 * 初始化page和size参数
	 * @param page 传入的page
	 * @param size 传入的size
	 * @param maxSize 每页最大的记录数
	 */
	public Map<String, Integer> initPageAndSize(String page, String size, int maxSize){
		Map<String, Integer> param = new HashMap<String, Integer>();
		if(StringUtils.isEmpty(size)){
			param.put("size", maxSize);
		}else{
			try {
				if(Integer.valueOf(size)>maxSize){
					param.put("size", maxSize);
				}else{
					param.put("size", Integer.valueOf(size));
				}
			} catch (Exception e) {
				param.put("size", maxSize);
			}
		}
		if(StringUtils.isEmpty(page)){
			param.put("page", 1);
		}else{
			try {
				param.put("page", Integer.valueOf(page));
			} catch (Exception e) {
				param.put("page", 1);
			}
		}
		return param;
	}

	public Map<String, Integer> initPageAndSize(Integer page, Integer size, int maxSize){
		return initPageAndSize(String.valueOf(page), String.valueOf(size), maxSize);
	}
	
	public Long getUid() {
		try{
			QaUsers user = getCurrentLoginedUser();
			return user != null ? user.getUid() : null;
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	public String getUserAvatarFile() {
		try{
			QaUsers user = getCurrentLoginedUser();
			return user != null ? user.getAvatarFile() : null;
		}catch (Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
